<template>
  <div class="message-panel">
    <div class="panel-header">
      <div class="panel-title">
        <el-icon><Bell /></el-icon>
        <span>系统消息</span>
      </div>
      <div class="panel-actions">
        <el-button type="primary" size="small" text @click="markAllRead">
          <el-icon><Check /></el-icon>全部已读
        </el-button>
        <el-dropdown @command="handleCommand">
          <el-button type="primary" size="small" text>
            <el-icon><MoreFilled /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="readAll">标记全部已读</el-dropdown-item>
              <el-dropdown-item command="clear">清空所有消息</el-dropdown-item>
              <el-dropdown-item command="settings">消息设置</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <div class="message-tabs">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="未读" name="unread">
          <template #label>
            未读
            <el-badge v-if="unreadCount > 0" :value="unreadCount" class="unread-badge" />
          </template>
        </el-tab-pane>
        <el-tab-pane label="系统通知" name="system"></el-tab-pane>
        <el-tab-pane label="任务提醒" name="task"></el-tab-pane>
      </el-tabs>
    </div>
    
    <div class="message-list" v-loading="loading">
      <template v-if="filteredMessages.length > 0">
        <div 
          v-for="message in filteredMessages" 
          :key="message.id" 
          :class="['message-item', {'unread': !message.read}]"
          @click="readMessage(message)"
        >
          <div class="message-icon">
            <el-icon v-if="message.type === 'system'" class="system-icon"><Setting /></el-icon>
            <el-icon v-else-if="message.type === 'task'" class="task-icon"><List /></el-icon>
            <el-icon v-else-if="message.type === 'alert'" class="alert-icon"><Warning /></el-icon>
            <el-icon v-else class="info-icon"><InfoFilled /></el-icon>
          </div>
          <div class="message-content">
            <div class="message-title">{{ message.title }}</div>
            <div class="message-body">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.time) }}</div>
          </div>
          <div class="message-actions">
            <el-button 
              type="primary" 
              link 
              size="small" 
              @click.stop="deleteMessage(message)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </template>
      <el-empty v-else description="暂无消息" />
    </div>
    
    <div v-if="filteredMessages.length > 0" class="panel-footer">
      <el-pagination
        layout="prev, pager, next"
        :total="totalMessages"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
        size="small"
      />
    </div>
    
    <!-- 消息设置对话框 -->
    <el-dialog
      v-model="settingsVisible"
      title="消息设置"
      width="400px"
    >
      <el-form label-width="120px">
        <el-form-item label="系统通知">
          <el-switch v-model="settings.system" />
        </el-form-item>
        <el-form-item label="任务提醒">
          <el-switch v-model="settings.task" />
        </el-form-item>
        <el-form-item label="安全警告">
          <el-switch v-model="settings.alert" />
        </el-form-item>
        <el-form-item label="桌面通知">
          <el-switch v-model="settings.desktop" />
        </el-form-item>
        <el-form-item label="声音提醒">
          <el-switch v-model="settings.sound" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settingsVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSettings">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 消息清空确认对话框 -->
    <el-dialog
      v-model="clearConfirmVisible"
      title="确认清空"
      width="300px"
    >
      <span>确定要清空所有消息吗？此操作不可恢复。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmClear">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Bell, Check, MoreFilled, Setting, List, Warning,
  InfoFilled, Delete
} from '@element-plus/icons-vue'
import { 
  getMessages, getUnreadCount, markAsRead, markAllAsRead, 
  deleteMessage as apiDeleteMessage, clearMessages,
  getMessageSettings, updateMessageSettings
} from '@/api/message'
import { Message, MessageSettings } from '@/types/message'

// 消息类型定义
interface Message {
  id: number
  title: string
  content: string
  time: string
  type: 'system' | 'task' | 'alert' | 'info'
  read: boolean
}

// 状态变量
const loading = ref(false)
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(5)
const settingsVisible = ref(false)
const clearConfirmVisible = ref(false)

// 消息设置
const settings = ref({
  system: true,
  task: true,
  alert: true,
  desktop: false,
  sound: false
})

// 模拟消息数据
const messages = ref<Message[]>([
  {
    id: 1,
    title: '系统升级通知',
    content: '系统将于今晚24:00进行升级维护，预计持续2小时，请提前做好准备。',
    time: '2025-06-26 10:30:00',
    type: 'system',
    read: false
  },
  {
    id: 2,
    title: '新用户注册提醒',
    content: '今日新增注册用户10名，请及时查看并审核。',
    time: '2025-06-26 09:15:00',
    type: 'info',
    read: true
  },
  {
    id: 3,
    title: '安全警告',
    content: '检测到异常登录行为，IP地址: 192.168.1.1，请确认是否为您本人操作。',
    time: '2025-06-25 18:45:00',
    type: 'alert',
    read: false
  },
  {
    id: 4,
    title: '待审核内容提醒',
    content: '有5篇新文章等待审核，请尽快处理。',
    time: '2025-06-25 15:30:00',
    type: 'task',
    read: false
  },
  {
    id: 5,
    title: '服务器状态预警',
    content: '服务器CPU使用率超过90%，请检查系统运行状态。',
    time: '2025-06-25 14:20:00',
    type: 'alert',
    read: true
  },
  {
    id: 6,
    title: '系统功能更新',
    content: '新增数据分析模块，提供更全面的数据统计和可视化功能。',
    time: '2025-06-24 11:00:00',
    type: 'system',
    read: false
  },
  {
    id: 7,
    title: '账户信息变更',
    content: '您的账户权限已更新，现在可以访问更多系统功能。',
    time: '2025-06-24 09:30:00',
    type: 'info',
    read: true
  },
  {
    id: 8,
    title: '定时任务完成',
    content: '数据库备份任务已成功完成，备份文件已保存至指定位置。',
    time: '2025-06-23 23:00:00',
    type: 'task',
    read: false
  },
  {
    id: 9,
    title: '用户反馈通知',
    content: '收到3条新的用户反馈，请及时查看并回复。',
    time: '2025-06-23 16:45:00',
    type: 'task',
    read: false
  },
  {
    id: 10,
    title: '系统公告',
    content: '端午节放假通知：6月10日至12日放假3天，13日正常上班。',
    time: '2025-06-23 10:15:00',
    type: 'system',
    read: true
  },
  {
    id: 11,
    title: '安全漏洞修复',
    content: '系统已完成安全漏洞修复，请更新至最新版本以确保系统安全。',
    time: '2025-06-22 14:30:00',
    type: 'alert',
    read: false
  },
  {
    id: 12,
    title: '存储空间警告',
    content: '系统存储空间已使用85%，请及时清理不必要的文件。',
    time: '2025-06-22 11:20:00',
    type: 'alert',
    read: true
  }
])

// 计算总消息数
const totalMessages = computed(() => {
  if (activeTab.value === 'all') {
    return messages.value.length
  } else if (activeTab.value === 'unread') {
    return messages.value.filter(msg => !msg.read).length
  } else {
    return messages.value.filter(msg => msg.type === activeTab.value).length
  }
})

// 计算未读消息数
const unreadCount = computed(() => {
  return messages.value.filter(msg => !msg.read).length
})

// 根据当前标签和分页过滤消息
const filteredMessages = computed(() => {
  let filteredList: Message[] = []
  
  if (activeTab.value === 'all') {
    filteredList = [...messages.value]
  } else if (activeTab.value === 'unread') {
    filteredList = messages.value.filter(msg => !msg.read)
  } else {
    filteredList = messages.value.filter(msg => msg.type === activeTab.value)
  }
  
  // 按时间排序（最新的在前面）
  filteredList.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
  
  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  
  return filteredList.slice(startIndex, endIndex)
})

// 加载消息数据
const loadMessages = () => {
  loading.value = true
  
  // 调用API获取消息列表
  getMessages({
    page: currentPage.value,
    pageSize: pageSize.value,
    type: activeTab.value
  }).then((response: any) => {
    loading.value = false
    if (response.data?.list) {
      messages.value = response.data.list
      totalMessages.value = response.data.total || 0
    }
  }).catch((error: any) => {
    loading.value = false
    console.error('获取消息失败', error)
  })
  
  // 更新未读消息数量
  fetchUnreadCount()
}

// 获取未读消息数量
const fetchUnreadCount = () => {
  getUnreadCount().then((response: any) => {
    unreadCount.value = response.data || 0
    emit('message-read', unreadCount.value)
  }).catch((error: any) => {
    console.error('获取未读消息数量失败', error)
  })
}

// 格式化时间显示
const formatTime = (timeString: string) => {
  const now = new Date()
  const msgTime = new Date(timeString)
  const diffDays = Math.floor((now.getTime() - msgTime.getTime()) / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    // 今天的消息，显示时间
    return timeString.split(' ')[1].substring(0, 5)
  } else if (diffDays === 1) {
    // 昨天的消息
    return '昨天 ' + timeString.split(' ')[1].substring(0, 5)
  } else if (diffDays < 7) {
    // 一周内的消息
    return `${diffDays}天前`
  } else {
    // 超过一周的消息，显示完整日期
    return timeString.substring(5, 16)
  }
}

// 阅读消息
const readMessage = (message: Message) => {
  if (!message.read) {
    markAsRead(message.id).then(() => {
      message.read = true
      ElMessage.success('已将消息标记为已读')
      // 更新未读消息数量
      fetchUnreadCount()
    }).catch(error => {
      console.error('标记消息为已读失败', error)
      ElMessage.error('标记消息为已读失败')
    })
  }
}

// 删除消息
const deleteMessage = (message: Message) => {
  ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    apiDeleteMessage(message.id).then(() => {
      const index = messages.value.findIndex(msg => msg.id === message.id)
      if (index !== -1) {
        messages.value.splice(index, 1)
      }
      ElMessage.success('删除成功')
      // 更新未读消息数量
      fetchUnreadCount()
    }).catch(error => {
      console.error('删除消息失败', error)
      ElMessage.error('删除消息失败')
    })
  }).catch(() => {})
}

// 标记所有消息为已读
const markAllRead = () => {
  markAllAsRead().then(() => {
    messages.value.forEach(msg => {
      msg.read = true
    })
    unreadCount.value = 0
    emit('message-read', 0)
    ElMessage.success('已将所有消息标记为已读')
  }).catch((error: any) => {
    console.error('标记所有消息为已读失败', error)
  })
}

// 处理下拉菜单命令
const handleCommand = (command: string) => {
  if (command === 'readAll') {
    markAllRead()
  } else if (command === 'clear') {
    clearConfirmVisible.value = true
  } else if (command === 'settings') {
    settingsVisible.value = true
  }
}

// 确认清空所有消息
const confirmClear = () => {
  clearMessages().then(() => {
    messages.value = []
    clearConfirmVisible.value = false
    ElMessage.success('已清空所有消息')
    // 更新未读消息数量
    fetchUnreadCount()
  }).catch(error => {
    console.error('清空消息失败', error)
    ElMessage.error('清空消息失败')
  })
}

// 保存消息设置
const saveSettings = () => {
  updateMessageSettings(settings.value).then(() => {
    settingsVisible.value = false
    ElMessage.success('设置已保存')
  }).catch(error => {
    console.error('保存设置失败', error)
    ElMessage.error('保存设置失败')
  })
}

// 加载消息设置
const loadSettings = () => {
  getMessageSettings().then(response => {
    if (response.data) {
      settings.value = response.data
    }
  }).catch(error => {
    console.error('获取消息设置失败', error)
  })
}

// 暴露给父组件的属性和方法
defineExpose({
  unreadCount,
  loadMessages,
  markAllRead
})

// 处理标签页切换
const handleTabChange = () => {
  currentPage.value = 1
  loadMessages()
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
}

// 组件挂载时加载数据
onMounted(() => {
  loadMessages()
})
</script>

<style scoped>
.message-panel {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.panel-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
  color: #409EFF;
}

.panel-actions {
  display: flex;
  gap: 8px;
}

.message-tabs {
  padding: 0 15px;
}

.unread-badge {
  margin-left: 4px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.message-item {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: flex-start;
  cursor: pointer;
  transition: background-color 0.3s;
}

.message-item:hover {
  background-color: #f5f7fa;
}

.message-item.unread {
  background-color: #ecf5ff;
}

.message-item.unread:hover {
  background-color: #e2efff;
}

.message-icon {
  margin-right: 12px;
  width: 36px;
  height: 36px;
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.system-icon {
  color: #409EFF;
  font-size: 18px;
}

.task-icon {
  color: #67C23A;
  font-size: 18px;
}

.alert-icon {
  color: #E6A23C;
  font-size: 18px;
}

.info-icon {
  color: #909399;
  font-size: 18px;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-title {
  font-weight: 600;
  margin-bottom: 6px;
  color: #303133;
}

.message-item.unread .message-title {
  color: #409EFF;
}

.message-body {
  font-size: 13px;
  color: #606266;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-actions {
  display: flex;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.message-item:hover .message-actions {
  opacity: 1;
}

.panel-footer {
  padding: 10px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 